#!/bin/bash

set -euo pipefail

# 加载本地敏感配置
ENV_FILE="$HOME/.docker_env.sh"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "[ERROR] Environment file not found: $ENV_FILE"
  exit 1
fi

echo "[INFO] Loading environment variables from $ENV_FILE"
# shellcheck source=/dev/null
source "$ENV_FILE"

# 检查基本环境变量
: "${DOCKER_PASSWORD:?Environment variable DOCKER_PASSWORD not set}"
: "${HARBOR_DOMAIN:?Environment variable HARBOR_DOMAIN not set}"

# 镜像列表来源判断
if [[ -n "${IMAGE_LIST_PATH:-}" ]]; then
  if [[ ! -f "$IMAGE_LIST_PATH" ]]; then
    echo "[ERROR] Local image list file not found: $IMAGE_LIST_PATH"
    exit 1
  fi
  IMAGE_LIST_FILE="$IMAGE_LIST_PATH"
  echo "[INFO] Using local image list file: $IMAGE_LIST_FILE"
elif [[ -n "${IMAGE_LIST_URL:-}" ]]; then
  IMAGE_LIST_FILE="/tmp/images.txt"
  echo "[INFO] Downloading image list from URL: $IMAGE_LIST_URL"
  curl -fsSL "$IMAGE_LIST_URL" -o "$IMAGE_LIST_FILE"
else
  echo "[ERROR] Either IMAGE_LIST_PATH or IMAGE_LIST_URL must be set in $ENV_FILE"
  exit 1
fi

# 登录 Harbor
echo "[INFO] Logging into Harbor registry..."
echo "$DOCKER_PASSWORD" | sudo docker login --username 'robot$proxy_update' --password-stdin reg.xiaokang.ink

# 推送函数
push_to_harbor() {
  local image="$1"
  local harbor_image="$HARBOR_DOMAIN/$(basename "$image")"

  echo "[INFO] Pulling: $image"
  sudo docker pull "$image"

  echo "[INFO] Tagging: $harbor_image"
  sudo docker tag "$image" "$harbor_image"

  echo "[INFO] Pushing: $harbor_image"
  sudo docker push "$harbor_image"
}

# 清理函数
clean_unused_images() {
  echo "[INFO] Cleaning unused Docker images..."
  sudo docker image prune -a -f
  echo "[INFO] Docker cleanup done."
}

# 主处理流程
batch=()
batch_index=1
while IFS= read -r line || [[ -n "$line" ]]; do
  line=$(echo "$line" | sed 's/#.*//')  # 去除注释
  line=$(echo "$line" | xargs)          # 去除前后空白
  if [[ -z "$line" ]]; then
    continue
  elif [[ "$line" == "###" ]]; then
    if [[ ${#batch[@]} -gt 0 ]]; then
      echo "[INFO] === Starting Batch $batch_index ==="
      for img in "${batch[@]}"; do
        push_to_harbor "$img"
      done
      clean_unused_images
      batch=()
      ((batch_index++))
    fi
  else
    batch+=("$line")
  fi
done < "$IMAGE_LIST_FILE"

# 处理最后一个批次
if [[ ${#batch[@]} -gt 0 ]]; then
  echo "[INFO] === Starting Final Batch $batch_index ==="
  for img in "${batch[@]}"; do
    push_to_harbor "$img"
  done
  clean_unused_images
fi

echo "[INFO] All image sync batches completed successfully."

